<template>
  <div>
    <span class="select-box" :span="7" v-for="(classify, index) in list" :key="index">
      <el-select v-loading="loading[index]" v-model="classifys[index]" filterable placeholder="请选择" @change="selected(index, $event)">
        <el-option v-for="item in classify" :key="item.id" :label="item.name" :value="item.id">
          <template>
            <span style="float: left">{{ item.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.id }}</span>
          </template>
        </el-option>
      </el-select>
    </span>
    <el-button icon="el-icon-close" @click="empty"> </el-button>
  </div>
</template>

<script>
import { classifyList, classifyParent } from '@/api/classify'

/**
 * 事件
 * change
 * 当用户选择分类时触发
 * 参数:
 * 包含所有分类id的数组
 */
export default {
  name: 'classify-select',
  props: {
    value: {
      type: [Number, String, undefined],
      default: undefined,
    },
  },
  data() {
    return {
      list: [[], [], []],
      classifys: [],
      loading: [],
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(v) {
        this.setid(v)
      },
    },
  },
  methods: {
    async getClassify(grade, parent) {
      this.loading[grade] = true
      const data = await classifyList({ grade, parent })
      this.loading[grade] = false
      if (data.code !== 200) return this.$message.error('获取分类列表失败，错误码:' + data.code)
      this.$set(this.list, grade, data.data)
      return data
    },
    selected(grade, value) {
      this.$emit('change', this.classifys)
      this.$emit('input', this.classifys[2])
      if (grade < 2) {
        this.getClassify(grade + 1, value)
        this.$set(this.classifys, grade + 1, undefined)
      }
    },
    empty() {
      this.classifys = []
      this.list[1] = []
      this.list[2] = []
      this.$emit('change', this.classifys)
      this.$emit('input', this.classifys[2])
    },
    async setid(v) {
      if (!v) return this.empty()
      if (v === this.classifys[2]) return
      const data = await classifyParent({ id: v })
      if (data.code !== 200) return this.$message.error('获取分类失败,错误码:' + data.code)
      for (let i = 0; i < data.data.length; i++) {
        const { id } = data.data[i]
        this.$set(this.classifys, i, id)
        if (i < 2) {
          await this.getClassify(i + 1, id)
        }
      }
      this.$emit('input', this.classifys[2])
    },
  },
  created() {
    this.getClassify(0)
  },
}
</script>

<style lang="scss" scoped>
.select-box {
  margin-right: 10px;
}
</style>
